<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="销售订单号" prop="clientOrderNumber">
        <el-input v-model="queryParams.clientOrderNumber" placeholder="请输入销售订单号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="单据日期" prop="date">
        <el-date-picker clearable v-model="queryParams.date" type="date" value-format="yyyy-MM-dd" placeholder="请选择单据日期">
        </el-date-picker>
      </el-form-item>
      <CustomSearch ref="ClientSelect2" label="客户名称" prop="clientName" labelWidth="110px" :tableKeys="ClientTableKeys2"
        formTitle="选择客户" primaryKey="clientName" showField="clientName" @getSearchList="getlistClient2"
        @updateQueryParams="updateQueryParamsForClient2" @selectDialogItem="selectDialogItemForClient2"></CustomSearch>
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="客户型号" prop="customerModel">
        <el-select v-model="queryParams.customerModel" placeholder="请选择审核状态" clearable>
          <el-option v-for="dict in dict.type.customer_model" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="颜色" prop="colour">
        <el-select v-model="queryParams.colour" filterable placeholder="请选择颜色" clearable>
          <el-option v-for="dict in dict.type.colour" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="audit">
        <el-select v-model="queryParams.audit" placeholder="请选择审核状态" clearable>
          <el-option v-for="dict in dict.type.audit" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="结案状态" prop="close">
        <el-select v-model="queryParams.close" placeholder="请选择结案状态" clearable>
          <el-option v-for="dict in dict.type.close" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:consignment:add']">新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:consignment:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="audit" plain size="mini" :disabled="single" @click="handleAudit"
          v-hasPermi="['system:consignment:audit']">审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="close" plain size="mini" :disabled="single" @click="Outbound"
          v-hasPermi="['system:consignment:storage ']">出库</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="close" plain size="mini" :disabled="single" @click="handleClose"
          v-hasPermi="['system:consignment:close ']">结案</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" @click="syncData">同步</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:consignment:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="consignmentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="发货通知单编码" align="center" prop="consignmentId" />
      <el-table-column label="出库类型" align="center" prop="types">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.outbound_types" :value="scope.row.types" />
        </template>
      </el-table-column>
      <el-table-column label="销售订单号" align="center" prop="clientOrderNumber" />
      <el-table-column label="单据日期" align="center" prop="date" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.date, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="客户" align="center" prop="clientName" />
      <el-table-column label="产品编码" align="center" prop="productId" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="规格型号" align="center" prop="specifications">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.specification_and_model" :value="scope.row.specifications" />
        </template>
      </el-table-column>
      <el-table-column label="客户型号" align="center" prop="customerModel">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.customer_model" :value="scope.row.customerModel" />
        </template>
      </el-table-column>
      <el-table-column label="颜色" align="center" prop="color">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.colour" :value="scope.row.colour" />
        </template>
      </el-table-column>
      <el-table-column label="出货仓库" align="center" prop="warehouseId" />
      <el-table-column label="应出库数量" align="center" prop="weekdaying" />
      <el-table-column label="已出库数量" align="center" prop="quantityShipped" />
      <el-table-column label="已回传数量" align="center" prop="returnNumber" />
      <el-table-column label="审核状态" align="center" prop="audit">
        <template #default="{ row }">
          <el-tag v-if="row.audit == 0" type="danger">未审核</el-tag>
          <el-tag v-if="row.audit == 2" type="success">已审核</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="结案状态" align="center" prop="close">
        <template #default="{ row }">
          <el-tag v-if="row.close == 0" type="danger">未结案</el-tag>
          <el-tag v-if="row.close == 2" type="success">已结案</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:consignment:edit']">修改</el-button> -->
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:consignment:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改发货通知单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="出库类型" prop="types">
          <el-select v-model="form.types" placeholder="请选择出库类型">
            <el-option v-for="dict in dict.type.outbound_types" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="销售订单号" prop="clientOrderNumber">
          <el-input v-model="form.clientOrderNumber" placeholder="请输入销售订单号" />
        </el-form-item>
        <CustomSearch ref="ClientSelect1" label="客户" prop="clientName" labelWidth="110px" :tableKeys="ClientTableKeys1"
          formTitle="选择客户" primaryKey="clientName" showField="clientName" @getSearchList="getlistClient1"
          @updateQueryParams="updateQueryParamsForClient1" @selectDialogItem="selectDialogItemForClient1"></CustomSearch>
        <el-form-item label="客户" prop="clientName">
          <el-input v-model="form.clientName" placeholder="请输入客户" />
        </el-form-item>
        <CustomSearch ref="ProductSelect1" label="产品" prop="productId" labelWidth="110px" :tableKeys="ProductTableKeys1"
          formTitle="选择产品" primaryKey="productId" showField="productName" @getSearchList="getlistProduct1"
          @updateQueryParams="updateQueryParamsForProduct1" @selectDialogItem="selectDialogItemForProduct1">
        </CustomSearch>
        <el-form-item label="产品编码" prop="productId">
          <el-input v-model="form.productId" placeholder="请输入产品编码" disabled />
        </el-form-item>
        <el-form-item label="颜色" prop="colour">
          <el-select v-model="form.colour" filterable placeholder="请选择颜色">
            <el-option v-for="dict in dict.type.colour" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <CustomSearch ref="WareHouseSearch2" label="默认仓库" prop="warehouseId" labelWidth="110px"
          :tableKeys="wareHouseTableKeys2" formTitle="选择仓库" primaryKey="warehouseId" showField="warehouseName"
          @getSearchList="getWareHouseSearchList2" @updateQueryParams="updateQueryParamsForWareHouse2"
          @selectDialogItem="selectDialogItemForWareHouse2"></CustomSearch>
        <el-form-item label="出货仓库" prop="warehouseId">
          <el-input v-model="form.warehouseId" placeholder="请输入出货仓库" />
        </el-form-item>
        <el-form-item label="应出库数量" prop="weekdaying">
          <el-input v-model.number="form.weekdaying" type="number" placeholder="请输入应出库数量"
            @blur="handleValueplannedQuantity" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listConsignment, getConsignment, delConsignment, addConsignment, updateAudit, updateClose, updateConsignment, syncData } from "@/api/outbound/consignment/consignment";
import { ClientSelect1 } from '@/mixins/client/cliemtSelectForForm.js'
import { ProductSelect1 } from '@/mixins/product/productSelectForForm.js'
import { wareHouseSelect2 } from '@/mixins/wareHouse/wareHouseSelectForForm.js'
import { ClientSelect2 } from '@/mixins/client/cliemtSelectForQueryParams.js'
import { Message } from "element-ui";
import CustomSearch from "@/views/commons/CustomSearch.vue";
export default {
  name: "Consignment",
  components: { CustomSearch },
  mixins: [ClientSelect1, ProductSelect1, wareHouseSelect2, ClientSelect2],

  dicts: ["outbound_types", "colour", "audit", "close", 'customer_model', 'carton_size', 'specification_and_model'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 发货通知单表格数据
      consignmentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        clientOrderNumber: null,
        date: null,
        clientName: null,
        productName: null,
        audit: null,
        close: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        warehouseId: [
          { required: true, message: "默认仓库不能为空", trigger: "blur" }
        ],
        productId: [
          { required: true, message: "产品不能为空", trigger: "blur" }
        ],
        types: [
          { required: true, message: "出库类型不能为空", trigger: "change" }
        ],
        weekdaying: [
          { required: true, message: "出库数量不能为空", trigger: "blur" }
        ],
        colour: [
          { required: true, message: "颜色不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    syncData() {
      let that = this
      this.$modal
        .confirm('是否进行数据同步？')
        .then(() => {
          that.$modal.loading('正在进行数据同步请耐心等待...')
          return syncData()
            .then((resp) => {
              console.log(resp);
              if (resp.code === 200) {
                that.getList()
                that.$modal.msgSuccess('数据同步成功')
              }
              that.$modal.closeLoading()
            })
            .catch(() => {
              that.$modal.closeLoading()
            })
        })
        .catch(() => {
          that.$modal.msg('已取消同步')
        })
    },
    /** 查询发货通知单列表 */
    getList() {
      this.loading = true;
      listConsignment(this.queryParams).then(response => {
        this.consignmentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        consignmentId: null,
        types: null,
        clientOrderNumber: null,
        date: null,
        clientName: null,
        productId: null,
        productName: null,
        color: null,
        warehouseId: null,
        weekdaying: null,
        quantityShipped: null,
        returnNumber: null,
        audit: null,
        close: null,
        remark: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.consignmentId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    //验证出库数量
    handleValueplannedQuantity() {
      this.form.weekdaying = parseInt(this.form.weekdaying)
      if (this.form.weekdaying <= 0) {
        this.form.weekdaying = 1
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加发货通知单";
    },
    //出库操作
    Outbound(row) {
      const consignmentId = row.consignmentId || this.ids
      getConsignment(consignmentId).then(response => {
        if (response.data.audit === 2) {
          this.$router.push({
            path: '/outbound/consignment/outbound-edit/index',
            query: { consignmentId: consignmentId[0] }
          })
        } else {
          Message.error("出库单未审核，无法进行出库")
        }
      });

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const consignmentId = row.consignmentId || this.ids
      getConsignment(consignmentId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改发货通知单";
      });
    },   /** 审核操作 */
    handleAudit(row) {
      this.reset();
      const consignmentId = row.consignmentId || this.ids;
      getConsignment(consignmentId).then(response => {
        if (response.data.audit == 2) {
          this.$modal.confirm('是否确认反审核编号为"' + consignmentId + '"的发货通知单').then(function () {
          }).then(() => {
            updateAudit(consignmentId).then(response => {
              if (response.code == 500) {
                Message.error(response.msg)
              } else {
                this.$modal.msgSuccess("反审核成功");
              }
            })
            this.getList();
            // this.$modal.msgSuccess("反审核成功");
          }).catch(() => { });
        } else {
          this.$modal.confirm('是否确认审核编号为"' + consignmentId + '"的发货通知单').then(function () {
            return updateAudit(consignmentId);
          }).then(() => {
            this.getList();
            this.$modal.msgSuccess("审核成功");
          }).catch(() => { });
        }
      });
    },
    /** 结案操作 */
    handleClose(row) {
      const consignmentId = row.consignmentId || this.ids;
      getConsignment(consignmentId).then(response => {
        if (response.data.close == 2) {
          this.$modal.confirm('是否确认反结案编号为"' + consignmentId + '"的发货通知单').then(function () {
            return updateClose(consignmentId);
          }).then(() => {
            this.getList();
            this.$modal.msgSuccess("反结案成功");
          }).catch(() => { });
        } else {
          this.$modal.confirm('是否确认结案编号为"' + consignmentId + '"的发货通知单').then(function () {
            return updateClose(consignmentId);
          }).then(() => {
            this.getList();
            this.$modal.msgSuccess("结案成功");
          }).catch(() => { });
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.consignmentId != null) {
            updateConsignment(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addConsignment(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const consignmentIds = row.consignmentId || this.ids;
      this.$modal.confirm('是否确认删除发货通知单编号为"' + consignmentIds + '"的数据项？').then(function () {
        return delConsignment(consignmentIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/consignment/export', {
        ...this.queryParams
      }, `consignment_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
